Popular Searches
Popular Course Categories
Popular Courses

Dart Functions

Dart Basics

Dart Functions

Functions are one of the most important concepts in Dart programming. A function is a reusable block of code designed to perform a specific task. Instead of writing the same code repeatedly, you can place it inside a function and call that function whenever required.

Functions are especially important in Flutter because application logic is divided into smaller, reusable operations such as calculating values, validating forms, processing user input, handling button actions, formatting data, and working with APIs.

JustAcademy's Flutter curriculum includes Functions & parameters as part of Dart Programming Fundamentals, along with variables, data types, operators, control statements, OOP, collections, and asynchronous programming. :contentReference[oaicite:0]{index=0}

1. What Is a Function?

A function is a named block of code that performs a particular task. Once a function is created, it can be called multiple times from different parts of a program.

Example

void greet() {
  print("Hello, Dart!");
}

void main() {
  greet();
}

Output:

Hello, Dart!

In this example, greet() is a function. When greet() is called, the code inside the function executes.

2. Why Use Functions?

Functions provide several important benefits:

  • Code reusability
  • Better code organization
  • Reduced code duplication
  • Easier debugging
  • Improved readability
  • Easier testing
  • Better separation of responsibilities
  • Useful for building scalable Flutter applications

3. Basic Function Syntax

returnType functionName() {
  // function body
}

Example:

void sayHello() {
  print("Hello!");
}

Here:

  • void is the return type.
  • sayHello is the function name.
  • () contains the parameters.
  • { } contains the function body.

4. Creating and Calling a Function

First, define the function:

void welcome() {
  print("Welcome to Dart Programming");
}

Then call it:

void main() {
  welcome();
}

5. Function Without Parameters

A function can perform a task without receiving any input.

void displayMessage() {
  print("Learning Dart Functions");
}

void main() {
  displayMessage();
}

6. Calling a Function Multiple Times

One of the major advantages of functions is that the same function can be called multiple times.

void greet() {
  print("Hello!");
}

void main() {
  greet();
  greet();
  greet();
}

Output:

Hello!
Hello!
Hello!

7. Function Parameters

Parameters allow a function to receive values from the code that calls it.

Example

void greet(String name) {
  print("Hello, $name!");
}

void main() {
  greet("Rahul");
}

Output:

Hello, Rahul!

Here, name is a parameter and "Rahul" is the argument passed to the function.

8. Parameter vs Argument

Parameter Argument
Defined in the function declaration Actual value passed during the function call
Example: String name Example: "Rahul"
void greet(String name) {
  print("Hello $name");
}

greet("Rahul");

name is the parameter, while "Rahul" is the argument.

9. Multiple Parameters

A function can accept multiple parameters.

void studentInfo(String name, int age) {
  print("Name: $name");
  print("Age: $age");
}

void main() {
  studentInfo("Rahul", 22);
}

10. Function with int Parameter

void printNumber(int number) {
  print("Number: $number");
}

void main() {
  printNumber(100);
}

11. Function with Multiple Numeric Parameters

void addNumbers(int a, int b) {
  print(a + b);
}

void main() {
  addNumbers(10, 20);
}

Output:

30

12. Positional Parameters

Normal parameters in Dart are positional parameters. Their values are assigned according to their position in the function call.

void student(String name, int age) {
  print("Name: $name");
  print("Age: $age");
}

student("Amit", 21);

Here, "Amit" is assigned to name and 21 is assigned to age.

13. Optional Positional Parameters

Optional positional parameters are placed inside square brackets [].

void greet(String name, [String? message]) {
  if (message != null) {
    print("$message, $name");
  } else {
    print("Hello, $name");
  }
}

void main() {
  greet("Rahul");
  greet("Priya", "Welcome");
}

14. Default Values for Optional Positional Parameters

An optional positional parameter can have a default value.

void greet(String name, [String message = "Hello"]) {
  print("$message, $name");
}

void main() {
  greet("Rahul");
  greet("Priya", "Welcome");
}

15. Named Parameters

Named parameters are placed inside curly braces {}. They allow arguments to be passed using parameter names.

void student({
  String? name,
  int? age,
}) {
  print("Name: $name");
  print("Age: $age");
}

void main() {
  student(
    name: "Rahul",
    age: 22,
  );
}

Named parameters make function calls easier to understand, especially when a function has several parameters.

16. Required Named Parameters

The required keyword can be used when a named parameter must be supplied by the caller.

void student({
  required String name,
  required int age,
}) {
  print("Name: $name");
  print("Age: $age");
}

void main() {
  student(
    name: "Rahul",
    age: 22,
  );
}

17. Optional Named Parameters

Named parameters are optional unless they are marked with required.

void profile({
  String? name,
  int? age,
}) {
  print("Name: $name");
  print("Age: $age");
}

void main() {
  profile(name: "Priya");
}

18. Default Values with Named Parameters

void order({
  required String product,
  int quantity = 1,
}) {
  print("Product: $product");
  print("Quantity: $quantity");
}

void main() {
  order(product: "Laptop");
  order(product: "Mobile", quantity: 2);
}

19. Positional vs Named Parameters

Positional Parameters Named Parameters
Values are passed according to position. Values are passed using parameter names.
Usually written directly inside (). Written inside {}.
Example: student("Rahul", 22) Example: student(name: "Rahul", age: 22)

20. Return Values

A function can return a value to the code that called it. The return type is written before the function name.

Example

int add(int a, int b) {
  return a + b;
}

void main() {
  int result = add(10, 20);
  print(result);
}

Output:

30

21. The return Keyword

The return keyword sends a value back to the caller and ends the current function execution.

int square(int number) {
  return number * number;
}

void main() {
  int result = square(5);
  print(result);
}

Output:

25

22. Function Returning String

String getMessage() {
  return "Welcome to Dart";
}

void main() {
  String message = getMessage();
  print(message);
}

23. Function Returning double

double calculatePrice(double price, double tax) {
  return price + tax;
}

void main() {
  double total = calculatePrice(1000, 180);
  print(total);
}

24. Function Returning bool

bool isAdult(int age) {
  return age >= 18;
}

void main() {
  bool result = isAdult(20);
  print(result);
}

25. void Functions

A function with the return type void does not return a useful value to the caller.

void showMessage() {
  print("Hello Dart");
}

26. Returning Values vs void

void Function Returning Function
Performs an action Calculates or produces a value
Does not return a useful result Uses return
Example: void printName() Example: int add()

27. Function with Conditional Return

String getResult(int marks) {
  if (marks >= 40) {
    return "Pass";
  }

  return "Fail";
}

void main() {
  print(getResult(75));
}

28. Early Return

A function can return early when a particular condition is satisfied.

String checkAge(int age) {
  if (age < 18) {
    return "Minor";
  }

  return "Adult";
}

void main() {
  print(checkAge(20));
}

29. Function Accepting a List

int calculateTotal(List numbers) {
  int total = 0;

  for (int number in numbers) {
    total += number;
  }

  return total;
}

void main() {
  List values = [10, 20, 30];

  print(calculateTotal(values));
}

Output:

60

30. Function Returning a List

List getNumbers() {
  return [10, 20, 30, 40];
}

void main() {
  List numbers = getNumbers();

  print(numbers);
}

31. Arrow Functions

Dart supports arrow functions, also called arrow syntax. They are useful for short functions containing a single expression.

Normal Function

int add(int a, int b) {
  return a + b;
}

Arrow Function

int add(int a, int b) => a + b;

The arrow function returns the value of the expression automatically.

32. Arrow Function Example

int square(int number) => number * number;

void main() {
  print(square(5));
}

33. Arrow Function Returning String

String greet(String name) => "Hello, $name";

void main() {
  print(greet("Rahul"));
}

34. Arrow Function Returning bool

bool isEven(int number) => number % 2 == 0;

void main() {
  print(isEven(10));
}

35. Arrow Function with Ternary Operator

String checkAge(int age) =>
    age >= 18 ? "Adult" : "Minor";

void main() {
  print(checkAge(20));
}

36. Normal Function vs Arrow Function

Normal Function Arrow Function
Uses curly braces Uses =>
Suitable for multiple statements Suitable for a single expression
Usually uses explicit return Expression result is returned automatically

37. When to Use Arrow Functions

Arrow functions are useful when the function contains one simple expression.

int doubleNumber(int number) => number * 2;

They are especially common with collection operations:

List numbers = [1, 2, 3, 4, 5];

numbers.forEach((number) => print(number));

38. Functions as Values

Dart treats functions as first-class objects. This means a function can be stored in a variable and passed to another function.

void greet() {
  print("Hello!");
}

void main() {
  var message = greet;

  message();
}

39. Function as a Parameter

A function can be passed as a parameter to another function. This is commonly used for callbacks.

void executeFunction(void Function() action) {
  action();
}

void sayHello() {
  print("Hello!");
}

void main() {
  executeFunction(sayHello);
}

40. Callback Example

void calculate(
  int a,
  int b,
  int Function(int, int) operation,
) {
  print(operation(a, b));
}

int add(int a, int b) {
  return a + b;
}

void main() {
  calculate(10, 20, add);
}

Output:

30

41. Using Anonymous Functions

An anonymous function is a function without a name.

void main() {
  List numbers = [1, 2, 3, 4, 5];

  numbers.forEach((number) {
    print(number);
  });
}

42. Anonymous Function with Arrow Syntax

void main() {
  List numbers = [1, 2, 3, 4, 5];

  numbers.forEach((number) => print(number));
}

43. Function with List Processing

List getEvenNumbers(List numbers) {
  List result = [];

  for (int number in numbers) {
    if (number % 2 == 0) {
      result.add(number);
    }
  }

  return result;
}

void main() {
  print(getEvenNumbers([1, 2, 3, 4, 5, 6]));
}

Output:

[2, 4, 6]

44. Function with Conditional Logic

String getGrade(int marks) {
  if (marks >= 90) {
    return "A+";
  } else if (marks >= 80) {
    return "A";
  } else if (marks >= 70) {
    return "B";
  } else if (marks >= 40) {
    return "Pass";
  } else {
    return "Fail";
  }
}

void main() {
  print(getGrade(85));
}

45. Function with Loops

int calculateSum(int n) {
  int sum = 0;

  for (int i = 1; i <= n; i++) {
    sum += i;
  }

  return sum;
}

void main() {
  print(calculateSum(10));
}

46. Function with Null Safety

Dart's null safety allows a function to specify whether its return value can be null.

String? findName(bool found) {
  if (found) {
    return "Rahul";
  }

  return null;
}

void main() {
  String? name = findName(false);

  print(name);
}

47. Practical Student Example

String calculateResult(int marks) {
  if (marks >= 40) {
    return "Pass";
  }

  return "Fail";
}

String calculateGrade(int marks) {
  if (marks >= 90) {
    return "A+";
  } else if (marks >= 80) {
    return "A";
  } else if (marks >= 70) {
    return "B";
  } else if (marks >= 60) {
    return "C";
  } else if (marks >= 40) {
    return "D";
  }

  return "F";
}

void main() {
  int marks = 82;

  print("Result: ${calculateResult(marks)}");
  print("Grade: ${calculateGrade(marks)}");
}

48. E-Commerce Function Example

double calculateTotal(double price, int quantity) {
  return price * quantity;
}

double calculateDiscount(double total) {
  if (total >= 5000) {
    return total * 0.10;
  }

  return 0;
}

void main() {
  double total = calculateTotal(1200, 5);
  double discount = calculateDiscount(total);

  double finalPrice = total - discount;

  print("Total: ₹$total");
  print("Discount: ₹$discount");
  print("Final Price: ₹$finalPrice");
}

49. Email Validation Function

bool isValidEmail(String email) {
  return email.contains("@") && email.contains(".");
}

void main() {
  String email = "[email protected]";

  if (isValidEmail(email)) {
    print("Valid email");
  } else {
    print("Invalid email");
  }
}

50. Functions in Flutter

Functions are used extensively in Flutter applications. They can handle button actions, form validation, calculations, data processing, navigation logic, API-related operations, and other application behavior.

Button Callback Example

void showMessage() {
  print("Button clicked!");
}

// Inside a Flutter widget
ElevatedButton(
  onPressed: showMessage,
  child: const Text("Click Me"),
)

Here, showMessage is passed as a callback to onPressed.

51. Flutter Form Validation Function

String? validateEmail(String? value) {
  if (value == null || value.isEmpty) {
    return "Email is required";
  }

  if (!value.contains("@")) {
    return "Enter a valid email";
  }

  return null;
}

Returning null can indicate that the value passed the validation in this example.

52. Functions for Reusable Flutter Logic

double calculateCartTotal(List prices) {
  double total = 0;

  for (double price in prices) {
    total += price;
  }

  return total;
}

Instead of repeating this calculation in multiple widgets or methods, the function can be reused wherever the calculation is required.

53. Function Naming Conventions

Use meaningful names that clearly describe what a function does.

Good Examples

calculateTotal();
validateEmail();
getUserData();
calculateDiscount();
showWelcomeMessage();
checkLoginStatus();

Less Descriptive Examples

doIt();
abc();
function1();
test();

Descriptive names make Dart and Flutter code easier to understand and maintain.

54. Common Mistakes with Functions

Mistake 1: Forgetting to Call the Function

void greet() {
  print("Hello");
}

Defining a function does not automatically execute it. You must call it:

greet();

Mistake 2: Incorrect Number of Arguments

void add(int a, int b) {
  print(a + b);
}

add(10);

This function requires two positional arguments.

Mistake 3: Incorrect Return Type

int getName() {
  return "Rahul";
}

The declared return type is int, but the function returns a String. The return type should match the returned value.

Correct Version

String getName() {
  return "Rahul";
}

55. Best Practices for Dart Functions

  • Give functions clear and meaningful names.
  • Keep each function focused on a specific responsibility.
  • Avoid unnecessarily large functions.
  • Use parameters instead of duplicating similar functions.
  • Use return types explicitly when they improve readability.
  • Use named parameters when a function has several optional inputs.
  • Use required for named parameters that must be provided.
  • Use arrow functions for short, single-expression functions.
  • Use null-safe types when a function can return or accept null.
  • Reuse functions instead of repeating the same logic.

56. Complete Dart Functions Example

String getGrade(int marks) {
  if (marks >= 90) {
    return "A+";
  } else if (marks >= 80) {
    return "A";
  } else if (marks >= 70) {
    return "B";
  } else if (marks >= 40) {
    return "Pass";
  }

  return "Fail";
}

double calculateTotal(double price, int quantity) {
  return price * quantity;
}

bool isEligible(int age) => age >= 18;

void studentInfo({
  required String name,
  required int age,
}) {
  print("Name: $name");
  print("Age: $age");
}

void main() {
  int marks = 85;

  print("Grade: ${getGrade(marks)}");

  double total = calculateTotal(1000, 3);
  print("Total: ₹$total");

  print("Eligible: ${isEligible(20)}");

  studentInfo(
    name: "Rahul",
    age: 22,
  );
}

57. Function Types at a Glance

Function Type Example Purpose
No parameters void greet() Performs a task without input
With parameters void greet(String name) Receives input
Returning value int add() Produces a result
Optional positional void test([int? value]) Allows optional positional input
Named parameters void test({String? name}) Allows named input
Required named void test({required String name}) Requires named input
Arrow function int square(int n) => n * n; Short single-expression function
Anonymous function (value) => print(value) Function without a declared name

58. Practice Exercises

  1. Create a function that prints your name.
  2. Create a function that accepts two numbers and prints their sum.
  3. Create a function that returns the square of a number.
  4. Create a function that checks whether a number is even or odd.
  5. Create a function that checks whether a person is eligible to vote.
  6. Create a function that calculates the total price of a product.
  7. Create a function that calculates a discount based on the purchase amount.
  8. Create a function that accepts a List of numbers and returns their total.
  9. Create a function that returns the largest number from a List.
  10. Create a function that returns only even numbers from a List.
  11. Create a function using named parameters for student information.
  12. Create a function using optional positional parameters.
  13. Convert a normal function into an arrow function.
  14. Create a function that validates an email address.
  15. Create a Flutter button callback function.

59. Quick Revision

Concept Meaning
Function Reusable block of code
Parameter Input defined by a function
Argument Actual value passed to a function
Return Sends a value back to the caller
void Function that does not return a useful value
Named parameter Parameter passed using its name
Optional parameter Parameter that does not always have to be provided
required Makes a named parameter mandatory
Arrow function Short function using =>
Callback A function passed to another function

60. Key Takeaways

  • Functions make Dart programs reusable and organized.
  • Functions can accept parameters and return values.
  • Parameters define the input expected by a function.
  • Arguments are the actual values passed to the function.
  • Dart supports positional, optional positional, and named parameters.
  • The required keyword can make named parameters mandatory.
  • The return statement sends a value back to the caller.
  • Arrow functions are useful for short, single-expression functions.
  • Functions can be passed as values and used as callbacks.
  • Functions are heavily used in Flutter for event handling, validation, calculations, data processing, and application logic.

61. Learn Flutter with JustAcademy

JustAcademy's Flutter training includes Dart Programming Fundamentals with variables, data types, operators, control statements, functions and parameters, OOP, collections, and asynchronous programming. :contentReference[oaicite:1]{index=1}

Explore the complete Flutter course: JustAcademy Flutter Training

Register for a course demo: JustAcademy Course Demo Registration

whatsapp